package com.zhb.services;

import com.google.common.collect.Lists;
import com.zhb.entity.ActivityInfo;
import com.zhb.entity.MyActivity;
import com.zhb.util.HtmlUtils;
import com.zhb.util.HttpUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.client.utils.DateUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.List;

/**
 * Created by jarvan4dev on 16/5/22.
 */
public class ActivityService {

    private final HttpClient httpClient;

    private static final String activityUri = "http://27.191.198.3:7888/action/web/integral.do?actionCmd=listReaderAction";

    private static final String allActivityUri = "http://27.191.198.3:7888/action/web/index.do?state=0";

    public ActivityService(HttpClient httpClient){
        this.httpClient = httpClient;
    }

    // 访问我的活动信息页面
    public String visitMyActivityPage() throws IOException {
        return HttpUtils.doGet(httpClient, activityUri);
    }

    // 进入活动详情页面
    private String visitActivityInfoPage(String activityInfoUri) throws IOException {
        return HttpUtils.doGet(httpClient, activityInfoUri);
    }

    /**
     * 获取我的活动
     * @param htmlSource
     * @return
     */
    public List<MyActivity> getMyActivities(String htmlSource) throws IOException {
        Document document = Jsoup.parse(HtmlUtils.formatHtml(htmlSource));
        Element activityTable = document.getElementsByTag("table").last();
        // 获得内容tr
        Elements trs = activityTable.getElementsByIndexGreaterThan(0);
        List<MyActivity> activityList = Lists.newArrayList();
        for (Element tr : trs){
            List<String> activityInfos = Lists.newArrayList();
            Elements tds = tr.children();
            for (Element td : tds){
                activityInfos.add(td.text());
            }
            //目前怀疑 活动名称一列是一个 <a></a> 可以获取里面的超链接, 然后活动进入详情
            String detailHtml = visitActivityInfoPage("");
            ActivityInfo activityDetail = getActivityInfo(detailHtml);
            MyActivity activityInfo = assembleActivityInfo(activityInfos, activityDetail);
            activityList.add(activityInfo);
        }
        return activityList;
    }

    // 访问所有活动信息页面
    public String visitAllActivityPage() throws IOException {
        return HttpUtils.doGet(httpClient, allActivityUri);
    }

    public  List<ActivityInfo> getAllActivities(String htmlSource) throws IOException {
        Document document = Jsoup.parse(HtmlUtils.formatHtml(htmlSource));
        List<ActivityInfo> activityDetailList = Lists.newArrayList();
        // 获取活动列表
        Elements activityListEles = document.select("div.fl_lf").select(".hdzx_div");
        for (Element activity : activityListEles){
            String activityDetailUri = "http://27.191.198.3:7888/action/web/" + activity.select("div.hdzx_a").attr("href");
            String infoHtml = visitActivityInfoPage(activityDetailUri);
            ActivityInfo activityInfo = getActivityInfo(infoHtml);
            activityDetailList.add(activityInfo);
        }
        return activityDetailList;
    }

    // 解析活动详情页
    private ActivityInfo getActivityInfo(String htmlSource) {
        ActivityInfo activityInfo = new ActivityInfo();
        Document document = Jsoup.parse(HtmlUtils.formatHtml(htmlSource));
        activityInfo.setCountQuota(Integer.parseInt(document.getElementsByClass("hdzx_sp_1").first().text()));
        activityInfo.setApplyCount(Integer.parseInt(document.getElementById("timeEnterForNum2").text()));
        activityInfo.setViewCount(Integer.parseInt(document.getElementById("viewId").text()));
        activityInfo.setThumbCount(Integer.parseInt(document.getElementById("commendId").text()));
        activityInfo.setFocusCount(Integer.parseInt(document.getElementById("focusId").text()));
        // 获取详细信息主体部分, 其中包含三个table, 第二个table没有任何作用
        Element gridItem = document.select("div.grid_item").first();
        // 获取信息主体部分包含的table
        Elements tables = gridItem.getElementsByTag("table");
        // 获取第一个包含信息的table, 里面包含了主要信息
        Element mainTable = tables.first();
        dealMainTable(mainTable, activityInfo);
        // 获取描述table
        Element descTable = tables.get(8);
        activityInfo.setActivityDesc(getContentFromTable(descTable));
        // 获取礼品table
        Element giftTable = tables.get(9);
        activityInfo.setActivityGift(getContentFromTable(giftTable));
        // 获取抽奖table
        Element awardTable = tables.get(11);
        activityInfo.setActivityAward(getContentFromTable(awardTable));
        //获取评论table
        Element commentTable = tables.get(11);
        activityInfo.setActivityComments(getContentFromTable(commentTable));
        return activityInfo;
    }

    // 提取第一个table中的信息,填充到ActivityInfo
    private void dealMainTable(Element mainTable, ActivityInfo activityInfo) {
        // 获取mainTable中众多子table, 简直是醉了,现在还有谁用table啊
        Elements subTables = mainTable.getElementsByTag("table");
        //获取包含img的table, 不是第0个, 而是第一个
        Element imgTable = subTables.get(1);
        // TODO 获取绝对路径
        String imgUri = imgTable.select("div").select("a").first().attr("href");
        activityInfo.setCoverLink(imgUri);
        // 获取包含活动名称,活动时间等信息的table
        Element infoTable = subTables.get(2);
        Elements infoTds = infoTable.getElementsByTag("td");
        fillActivityInfo(infoTds, activityInfo);
    }

    // 填充信息
    private void fillActivityInfo(Elements infoTds, ActivityInfo activityInfo) {
        activityInfo.setName(infoTds.get(0).text());
        activityInfo.setCategory(infoTds.get(1).text().split(":")[1]);
        activityInfo.setBelongLib(infoTds.get(2).text().split(":")[1]);

        //这一栏比较特殊, 包含了时间和状态(发布日期:2016-05-17 状态:评分)
        String timeStatus = infoTds.get(3).text();
        activityInfo.setPublishDate(timeStatus.split(" ")[0].split(":")[1]);
        activityInfo.setStatus(timeStatus.split(" ")[1].split(":")[1]);

        activityInfo.setSignTime(infoTds.get(4).text().substring(5));
        activityInfo.setActivityTime(infoTds.get(5).text().substring(5));
        activityInfo.setScore(infoTds.get(7).text().split(":")[1]);

        // 第8个td比较特殊
        activityInfo.setActivityAddr(infoTds.get(8).getElementsByTag("td").get(2).text());
    }


    // 提取描述table中的信息
    private String getContentFromTable(Element descTable) {
        String desc = descTable.getElementsByTag("div").first().text();
        return desc;
    }

    private MyActivity assembleActivityInfo(List<String> activityInfos, ActivityInfo activityInfo) {
        MyActivity myActivity = new MyActivity();
        myActivity.setApplyTime(DateUtils.parseDate(activityInfos.get(0)));
        myActivity.setAttendance(activityInfos.get(0));
        myActivity.setAttendScore(Integer.parseInt(activityInfos.get(0)));
        myActivity.setPerformScore(Integer.parseInt(activityInfos.get(0)));
        myActivity.setTotalScore(Integer.parseInt(activityInfos.get(0)));
        myActivity.setStatus(activityInfos.get(0));
        myActivity.setActivityInfo(activityInfo);
        return myActivity;
    }
}
